<?php


namespace App\Http\Controllers\Admin\Channel;


use App\Response\Response;
use Illuminate\Http\Request;
use App\Exceptions\BasicException;
use App\Services\Tools\ExportService;
use App\Http\Controllers\BaseController;

class ChannelStageController extends BaseController
{
    /**
     * @api {post} /channel/stage 添加渠道分期
     *
     * @apiGroup 渠道分期
     *
     * @apiParam {int} channel_id 渠道id，必须
     * @apiParam {string} stage_name 渠道名称，必须
     * @apiParam {int} promote_url_type 分发（推广）链接类型：1：H5；2：渠道包，必须
     * @apiParam {int} channel_bag_type 渠道包类型：1：安卓；2：ios；3：安卓ios二合一，当promote_url_type=2时必须
     * @apiParam {string} remark 备注
     * @apiParam {string} room_ids 默认房间id，多个用英文逗号隔开
     * @apiParam {int} status 状态：1：启用；0：禁用，必须
     *
     * @apiSuccessExample 成功响应
     * {"code":200,"data":[]}
     */
    public function add(Request $request)
    {
        $param = $request->only('channel_id', 'stage_name', 'promote_url_type', 'channel_bag_type', 'remark', 'room_ids', 'status');
        $v = app('validator')->make($param, [
            'channel_id' => 'required|integer',
            'stage_name' => 'required|string|max:20',
            'promote_url_type' => 'required|integer|in:1,2',
            'channel_bag_type' => 'required_if:promote_url_type,2|integer|in:1,2,3',
            'remark' => 'string|max:50',
            'status' => 'required|integer|in:0,1',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $res = app('repo_channel')->addOrEditStage($param);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '添加失败');
    }

    /**
     * @api {put} /channel/stage 编辑渠道分期
     *
     * @apiGroup 渠道分期
     *
     * @apiParam {int} id 渠道分期id，必须
     * @apiParam {int} channel_id 渠道id，必须
     * @apiParam {string} stage_name 渠道名称，必须
     * @apiParam {int} promote_url_type 分发（推广）链接类型：1：H5；2：渠道包，必须
     * @apiParam {int} channel_bag_type 渠道包类型：1：安卓；2：ios；3：安卓ios二合一，当promote_url_type=2时必须
     * @apiParam {string} remark 备注
     * @apiParam {string} room_ids 默认房间id，多个用英文逗号隔开
     * @apiParam {int} status 状态：1：启用；0：禁用，必须
     *
     * @apiSuccessExample 成功响应
     * {"code":200,"data":[]}
     */
    public function edit(Request $request)
    {
        $param = $request->only('id', 'stage_name', 'promote_url_type', 'channel_bag_type', 'remark', 'room_ids', 'status');
        $v = app('validator')->make($param, [
            'id' => 'required|integer',
            'stage_name' => 'required|string|max:20',
            'promote_url_type' => 'required|integer|in:1,2',
            'channel_bag_type' => 'required_if:promote_url_type,2|integer|in:1,2,3',
            'remark' => 'string|max:50',
            'status' => 'required|integer|in:0,1',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $res = app('repo_channel')->addOrEditStage($param);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '添加失败');
    }

    /**
     * @api {get} /channel/stage 渠道分期列表
     *
     * @apiGroup 渠道分期
     *
     * @apiParam {int} channel_id 渠道id，必须
     * @apiParam {int} stage_id 渠道分期ID
     * @apiParam {string} stage_name 渠道分期名称
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 2, 渠道分期ID
    "channel_id": 1,
    "stage_name": "二分期", 渠道分期名称
    "promote_url_type": 2, 分发模式：1：H5链接；2：渠道包
    "promote_url": "http://news.baidu.com/", 渠道推广链接
    "bag_type": 1, 渠道包类型：1：安卓；2：ios；3：安卓ios二合一
    "remark": "2-3月", 备注
    "room_ids": "5437434,579833,5524777", 默认进房id
    "status": 1, 状态：1：可用；0：禁用
    "channel_stage_data": {
    "channel_stage_id": 2,
    "register_user_count": 149995, 注册成功数
    "activated_user_count": 149995, 登录激活数
    "recharge_user_count": 2577, 充值成功用户数
    "recharge_total": 484613 充值总金额
    },
    "channel_name": "头条" 所属渠道名称
    }
    ],
    "first_page_url": "http://local.channel/channel/stage?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.channel/channel/stage?page=1",
    "next_page_url": null,
    "path": "http://local.channel/channel/stage",
    "per_page": 10,
    "prev_page_url": null,
    "to": 2,
    "total": 2
    }
    }
     */
    public function list(Request $request)
    {
        $param = $request->only('channel_id', 'stage_id', 'stage_name', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'channel_id' => 'required|integer|min:1',
            'stage_id' => 'integer|min:1',
            'stage_name' => 'string',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $channelId = $param['channel_id'];
        $stageId = $param['stage_id'] ?? 0;
        $stageName = $param['stage_name'] ?? '';
        $pageSize= $param['page_size'] ?? 10;

        $where = [['channel_id', '=', $channelId]];
        if ($stageId > 0) {
            $where[] = ['id', '=', $stageId];
        }
        if ($stageName) {
            $where[] = ['name', 'like', "%$stageName%"];
        }

        $list = app('model_channel_stage')
            ->select('id', 'channel_id', 'name as stage_name', 'promote_url_type', 'promote_url', 'bag_type', 'remark', 'room_ids', 'status')
            ->where($where)
            ->with(['channel_stage_data' => function($query) {
                $query->select('channel_stage_id', 'register_user_count', 'activated_user_count', 'recharge_user_count', 'recharge_total');
            }])
            ->orderBy('id', 'desc')
            ->paginate($pageSize)->toArray();

        //批量查询渠道名称
        $channelIds = array_column($list['data'], 'channel_id');
        $channels = app('model_channel')->select('name', 'id')->whereIn('id', $channelIds)->pluck('name', 'id')->toArray();
        foreach ($list['data'] as &$v) {
            $v['channel_name'] = $channels[$v['channel_id']];
        }

        return Response::sendData($list);
    }

    /**
     * @api {get} /channel/stage/detail 渠道分期详情
     *
     * @apiGroup 渠道分期
     *
     * @apiParam {int} id 渠道分期id，必须
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "id": 2, 分期id
    "channel_id": 1,
    "stage_name": "二分期", 分期名称
    "promote_url_type": 2, 分发类型：1：H5链接；2：渠道包
    "promote_url": "https://www.baidu.com/channel_bag?channel_stage_id=18", 渠道推广链接
    "bag_type": 1, 渠道包类型：1：安卓；2：ios；3：安卓ios二合一
    "bag_download_url": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/app/qpxq/channel/stage18.apk", 渠道包下载链接
    "remark": "2-3月", 备注
    "status": 1, 状态：1：启用；0：禁用
    "channel_name": "头条", 所属渠道名称
    "channel_stage_data": {
    "channel_stage_id": 2,
    "register_user_count": 149995, 注册用户数
    "activated_user_count": 149995, 登录激活用户数
    "recharge_user_count": 2577, 充值成功用户数
    "recharge_total": 484613 充值总金额
    }
    }
    }
     */
    public function detail(Request $request)
    {
        $param = $request->only('id');
        $v = app('validator')->make($param, [
            'id' => 'required|integer',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $stage = app('model_channel_stage')
            ->select('id', 'channel_id', 'name as stage_name', 'promote_url_type', 'promote_url', 'bag_type', 'bag_download_url', 'remark', 'status')
            ->with(['channel_stage_data' => function($query) {
                $query->select('channel_stage_id', 'register_user_count', 'activated_user_count', 'recharge_user_count', 'recharge_total');
            }])
            ->where('id', $param['id'])->first();
        if (empty($stage)) throw new BasicException(0, '分期id错误，分期不存在');

        $stage->channel_name = app('model_channel')->where('id', $stage->channel_id)->value('name');
        return Response::sendData($stage);
    }

    /**
     * @api {get} /channel/stage/user 渠道分期用户列表
     *
     * @apiGroup 渠道分期
     *
     * @apiParam {int} channel_stage_id 渠道分期id，必须
     * @apiParam {string} register_time_start 注册时间开始，秒级时间戳
     * @apiParam {string} register_time_end 注册时间结束，秒级时间戳
     * @apiParam {string} last_login_time_start 最后登录时间开始，秒级时间戳
     * @apiParam {string} last_login_time_end 最后登录时间结束，秒级时间戳
     * @apiParam {int} keep_date 留存日期，-1（默认）：不限制；2/3/7/15分别表示第二/三/七/十五日留存
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，默认10
     * @apiParam {int} order_by_recharge_money 充值金额排序：-1：降序；0：不按充值金额排序；1：升序
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "user_id": 547175, 用户索引id
    "mobile": "13018728993", 手机号
    "register_time": "2019-11-09 16:24:15", 注册时间
    "last_login_time": "2021-08-27 10:14:27", 最后登录时间
    "user_code": 661214, 用户ID
    "nickname": "加勒比海盗" 昵称
    "recharge_total": 0, 充值金额
    "earnings_total": 0, 收益
    "watch_live_duration": "3.1" 观看直播时长，单位：小时
    }
    ],
    "first_page_url": "http://local.channel/channel/stage/user-list?page=1",
    "from": 1,
    "last_page": 102661,
    "last_page_url": "http://local.channel/channel/stage/user-list?page=102661",
    "next_page_url": "http://local.channel/channel/stage/user-list?page=2",
    "path": "http://local.channel/channel/stage/user-list",
    "per_page": "1",
    "prev_page_url": null,
    "to": 1,
    "total": 102661,
    "statistics_data": {
    "register_user_count": 3, 注册用户数
    "activate_user_count": 3, 登录激活用户数
    "recharge_user_count": 2, 充值用户数
    "recharge_total": "0.03" 充值总额
    }
    }
    }
     */
    public function userList(Request $request)
    {
        $param = $request->only('channel_stage_id', 'register_time_start', 'register_time_end', 'last_login_time_start', 'last_login_time_end', 'keep_date', 'page', 'page_size', 'order_by_recharge_money');
        $v = app('validator')->make($param, [
            'channel_stage_id' => 'required|integer',
            'register_time_start' => 'integer',
            'register_time_end' => 'integer',
            'last_login_time_start' => 'integer',
            'last_login_time_end' => 'integer',
            'keep_date' => 'integer|in:-1,2,3,7,15',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
            'order_by_recharge_money' => 'integer|in:-1,0,1',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $list = app('repo_channel')->channelStageUserList($param);

        return Response::sendData($list);
    }

    /**
     * @api {get} /channel/stage/user/export 渠道分期用户列表导出
     *
     * @apiGroup 渠道分期
     *
     * @apiParam {int} channel_stage_id 渠道分期id，必须
     * @apiParam {string} register_time_start 注册时间开始，秒级时间戳
     * @apiParam {string} register_time_end 注册时间结束，秒级时间戳
     * @apiParam {string} last_login_time_start 最后登录时间开始，秒级时间戳
     * @apiParam {string} last_login_time_end 最后登录时间结束，秒级时间戳
     * @apiParam {int} keep_date 留存日期，-1：不限制；2/3/7/15分别表示第二/三/七/十五日留存
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "download_url": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/channel/data_excel/渠道分期用户列表20210903112531.xlsx"
    }
    }
     */
    public function userListExport(Request $request)
    {
        ini_set('memory_limit', '1024M');

        $param = $request->only('channel_stage_id', 'register_time_start', 'register_time_end', 'last_login_time_start', 'last_login_time_end', 'keep_date');
        $v = app('validator')->make($param, [
            'channel_stage_id' => 'required|integer|min:1',
            'register_time_start' => 'integer',
            'register_time_end' => 'integer',
            'last_login_time_start' => 'integer',
            'last_login_time_end' => 'integer',
            'keep_date' => 'integer|in:-1,2,3,7,15',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $list = app('repo_channel')->channelStageUserData($param);

        $headings = [
            'mobile' => '手机号',
            'register_time' => '注册时间',
            'last_login_time' => '最后登录时间',
            'user_code' => '用户ID',
            'nickname' => '昵称',
            'recharge_total' => '充值金额',
            'earnings_total' => '收益',
        ];

        $filename = '/channel/data_excel/' . 'channel_stage_user' . date('YmdHis') . '.xlsx';
        $res = app('excel')->store(new ExportService($list, $headings), $filename, 'oss', 'Xlsx');
        if (!$res) throw new BasicException(0, '导出失败');

        return Response::sendData([
            "download_url" => 'https://'.env('OSS_BUCKET').'.'.env('OSS_ENDPOINT').$filename,
        ]);
    }

    /**
     * @api {get} /channel/stage/user/recharge 渠道分期用户详情（充值列表）
     *
     * @apiGroup 渠道分期
     *
     * @apiParam {int} user_id 用户索引id，必须
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 765, 索引id
    "order_sn": "20191109909341831787", 订单号
    "money": "1.00", 充值金额
    "gold": 1, 获得金币数量
    "status": 2, 状态：1：待支付；2：已支付
    "type": 1, 充值方式：1.支付宝 2.微信 3.苹果内购 4.h5支付宝 5.h5微信
    "pay_time": "2019-11-09 17:15:46", 支付时间
    "add_time": "2019-11-09 17:15:34", 创建时间
    "trade_no": "2019110922001490120512420425", 交易号
    "merchant_type": 1,
    "merchant_name": "微信鱼糖" 收款账号
    }
    ],
    "first_page_url": "http://local.channel/channel/stage/user/recharge?page=1",
    "from": 1,
    "last_page": 604,
    "last_page_url": "http://local.channel/channel/stage/user/recharge?page=604",
    "next_page_url": "http://local.channel/channel/stage/user/recharge?page=2",
    "path": "http://local.channel/channel/stage/user/recharge",
    "per_page": "1",
    "prev_page_url": null,
    "to": 1,
    "total": 604
    }
    }
     */
    public function userRechargeList(Request $request)
    {
        $param = $request->only('user_id', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'user_id' => 'required|integer',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $userId = $param['user_id'];
        $pageSize = $param['page_size'] ?? 10;

        $list = app('model_user_recharge')
            ->select('id', 'order_sn', 'money', 'gold', 'status', 'type', 'pay_time', 'add_time', 'trade_no', 'merchant_type')
            ->where('user_id', $userId)
            ->orderBy('id', 'desc')
            ->paginate($pageSize);

        //查询收款账户
        $payMerchants = app('model_pay_merchant')->select('name', 'id')->pluck('name', 'id')->toArray();

        foreach ($list as &$v) {
            $v->merchant_name = $payMerchants[$v->merchant_type] ?? '';

            $v->pay_time = $v->pay_time > 0 ? date('Y-m-d H:i:s', $v->pay_time) : '';
            $v->add_time = date('Y-m-d H:i:s', $v->add_time);
        }
        return Response::sendData($list);
    }

    /**
     * @api {get} /channel/stage/bag-url 获取渠道分期包地址
     *
     * @apiGroup 渠道分期
     *
     * @apiParam {int} id 渠道分期id，必须
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "bag_download_url": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/app/qpxq/channel/test/stage13.apk",
    "paste_content": "channel_stage_id8"
    }
    }
     */
    public function getBagUrl(Request $request)
    {
        $param = $request->only('id');
        $v = app('validator')->make($param, [
            'id' => 'required|integer',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $stage = app('model_channel_stage')
            ->select('bag_download_url')
            ->where('id', $param['id'])->first();
        if (empty($stage)) throw new BasicException(0, '分期id错误，分期不存在');

        $stage->paste_content = 'channel_stage_id' . $param['id'];
        return Response::sendData($stage);
    }

    /**
     * @api {get} /channel/stage/list-by-channelid 获取渠道分期列表（通过渠道id）
     *
     * @apiGroup 渠道分期
     *
     * @apiParam {int} channel_id 渠道id，必须
     *
     * @apiSuccessExample 成功响应
     * [
    {
    "channel_stage_id": 3, 渠道分期id
    "name": "分期2" 分期名称
    },
    {
    "channel_stage_id": 4,
    "name": "分期3"
    }
    ]
     */
    public function listByChannelId(Request $request)
    {
        $param = $request->only('channel_id');
        $v = app('validator')->make($param, [
            'channel_id' => 'required|integer',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $channelId = $param['channel_id'];

        $data = app('model_channel_stage')->select('id as channel_stage_id', 'name')->where('channel_id', $channelId)->get();
        return $data;
    }
}